package com.gxar.file.server.base.controller;

import com.gxar.common.entity.Result;
import com.gxar.common.entity.login.LoginUserThread;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.file.server.base.common.enums.ProductEnum;
import com.gxar.file.server.base.model.ResultCodeEnum;
import com.gxar.file.server.base.model.upload.request.FilePartUploadRequest;
import com.gxar.file.server.base.model.upload.response.FilePartUploadResponse;
import com.gxar.file.server.db.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.Optional;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/8/14 10:13
 */
@Api(tags = "文件分片视图控制器")
@RestController
@RequestMapping("/api/file/part")
@RequiredArgsConstructor
@Slf4j
public class FilePartController {

    private final FileService fileService;

    @ApiOperation("上传文件")
    @PostMapping(value = "/upload")
    @ResponseBody
    public Result<FilePartUploadResponse> upload(@Valid FilePartUploadRequest uploadRequest, @RequestParam(name = "file", required = false) MultipartFile file) {
        try {
            UserProfile userProfile = LoginUserThread.get();
            if (file != null) {
                Optional<ProductEnum> productEnumOptional = ProductEnum.getByName(uploadRequest.getProduct());
                if (!productEnumOptional.isPresent()) {
                    return Result.error(ResultCodeEnum.TEMPORARILY_UNAVAILABLE);
                }
                ProductEnum product = productEnumOptional.get();
                //图片文件处理
                String originalFilename = file.getOriginalFilename();
                String suffix = null;
                if (StringUtils.isNotBlank(originalFilename)) {
                    suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                if (StringUtils.isNotBlank(originalFilename)) {
                    originalFilename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                }
                StringBuilder directory = new StringBuilder();
                if (Objects.nonNull(userProfile)) {
                    directory.append("/").append(userProfile.getId());
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(uploadRequest.getDirectory())) {
                    String fileDirectory = uploadRequest.getDirectory();
                    if (fileDirectory.startsWith("/")) {
                        fileDirectory = fileDirectory.substring(1);
                    }
                    if (fileDirectory.endsWith("/")) {
                        fileDirectory = fileDirectory.substring(0, fileDirectory.length() - 1);
                    }
                    directory.append("/").append(fileDirectory);
                }
                String name = "product/" + product.getName() + directory + "/" + originalFilename + "-" + System.currentTimeMillis() + suffix;
                if (StringUtils.isNotBlank(uploadRequest.getKey())) {
                    name = uploadRequest.getKey();
                }
                return Result.success(fileService.uploadPart(product, name, originalFilename, file, uploadRequest, userProfile));
            }
        } catch (Exception e) {
            log.error("文件上传异常：{}", e.getMessage(), e);
            return Result.error(ResultCodeEnum.UPLOAD_EXCEPTION);
        }
        return Result.success();
    }
}
